package cn.com.twoke.get_xml_data.service.impl;

import cn.com.twoke.get_xml_data.entity.TestPlanReport;
import cn.com.twoke.get_xml_data.entity.TestReport;
import cn.com.twoke.get_xml_data.entity.TestReportHeader;
import cn.com.twoke.get_xml_data.service.GetXmlDataHandler;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DefaultGetXmlDataHandler implements GetXmlDataHandler {

    @Override
    public TestPlanReport handle(String fileNo, File file) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        TestPlanReport.TestPlanReportBuilder builder = TestPlanReport.builder();
        Element testPlanReport = document.getRootElement();
        Element tph = testPlanReport.element("testplanheader");

        TestReportHeader header = TestReportHeader.builder()
                .numberOfTestCases(tph.elementText("numberoftestcases"))
                .numberOfPassVerdicts(tph.elementText("numberofpassverdicts"))
                .numberOfFailVerdicts(tph.elementText("numberoffailverdicts"))
                .numberOfInconcVerdicts(tph.elementText("numberofinconcverdicts"))
                .numberOfOtherVerdicts(tph.elementText("numberofotherverdicts"))
                .build();
        builder.testReportHeader(header);

        Element testReports = testPlanReport.element("testreports");
        List<TestReport> testReportList = new ArrayList<>();
        for (Element tr : testReports.elements("testreport")) {
            testReportList.add(TestReport.builder()
                    .testReportNumber(tr.elementText("testreportnumber"))
                    .testcase(tr.elementText("testcase"))
                    .finalVerdict(tr.element("finalverdict").attributeValue("result"))
                    .testCaseVersion(tr.elementText("testcaseversion"))
                    .extTestReportType(tr.element("exttestreport").attributeValue("type"))
                    .extTestReportLink(tr.element("exttestreport").attributeValue("link"))
                    .build());
        }
        builder.testReports(testReportList);
        TestPlanReport report = builder.build();
        this.handle(fileNo, file, report);
        return report;
    }


    protected void handle(String fileNo, File file, TestPlanReport testPlanReport) {

    };
}
